 //
//  YCLoginViewController.m
//  YCVillageDoctor
//
//  Created by Mac on 2017/6/7.
//  Copyright © 2017年 zhangxiaoliang. All rights reserved.
//

#import "YCLoginViewController.h"
#import "RegisterViewController.h"
#import "ForgetViewController.h"
#import "ResetPhoneViewController.h"
#import "YCTabbarViewController.h"
#define kIPHONE6_HIGHT 675
#import "YCSSKeychain.h"

@interface YCLoginViewController ()
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *regristerBtn;
@property (weak, nonatomic) IBOutlet UIButton *forgetBtn;
@property (strong, nonatomic) IBOutlet UIView *userview;
@property (strong, nonatomic) IBOutlet UIView *pwdview;
@property (strong, nonatomic) IBOutlet UITextField *userTextfield;
@property (strong, nonatomic) IBOutlet UITextField *pwdTextfield;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *ImageHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *margenHeight;

@property (weak, nonatomic) IBOutlet UIImageView *loginTopImageView;



@end

@implementation YCLoginViewController

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];

    self.userTextfield.text = [[NSUserDefaults standardUserDefaults] valueForKey:@"link_mobile"];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
 
    
    self.userTextfield.clearButtonMode=UITextFieldViewModeAlways;
    self.pwdTextfield.clearButtonMode =UITextFieldViewModeAlways;
    self.userTextfield.userInteractionEnabled  =YES;
    self.pwdTextfield.userInteractionEnabled  =YES;
    
    self.loginTopImageView.layer.cornerRadius = 10;
    self.loginTopImageView.layer.masksToBounds = YES;
    
    //MARK:-设置光标颜色
    [[UITextField appearance] setTintColor:[UIColor colorWithHexString:@"CCCCCC"]];
    self.loginBtn.backgroundColor = login_BackgroundColor;
    self.loginBtn.layer.masksToBounds =  YES;
    self.loginBtn.layer.cornerRadius = 5;
    
    
    if (kScreenWidth == 320) {
        self.ImageHeight.constant =80;
    }
    
    if (kScreenWidth == 320) {
        self.margenHeight.constant = kScreenHeight * 80.0/kIPHONE6_HIGHT;
    }
    
    [self setTextfield];
    
    //修改状态栏字体原色
    [UIApplication sharedApplication].statusBarStyle= UIStatusBarStyleLightContent;
}

/**
 *  设置Textfield
 
 */
-(void)setTextfield{
    
    [self.userTextfield addTarget:self action:@selector(validationChanged:) forControlEvents:UIControlEventEditingChanged];
    self.userTextfield.text = self.usephone;
    self.pwdTextfield.textColor=[UIColor blackColor];
    [UITextField setupColorWith:@[self.userTextfield,self.pwdTextfield]];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)regriterClick:(id)sender {
    
    RegisterViewController *regVC = [[RegisterViewController alloc]init];
    
    [self presentViewController:regVC animated:YES completion:nil];
    
}

- (IBAction)forgetClick:(id)sender {
    
    ForgetViewController *forVC = [[ForgetViewController alloc]init];
    
    [self presentViewController:forVC animated:YES completion:^{
        
    }];
}
- (IBAction)loginClick:(id)sender {
    
    [self.view endEditing:YES];
    
    if (![YCCommonTool validatePhoneNumber:self.userTextfield.text]) {
        [self presentFailureTips:@"手机格式不对"];
        return ;
    }
    
    if (![YCCommonTool validatePassword:self.pwdTextfield.text]) {
        [self presentFailureTips:@"密码格式不对"];
        return ;
    }
    
    [self userlogin];
    
}

//MARK: - 用户登录
-(void)userlogin {
    
    __weak typeof(self)WeakSekf = self;
    
    [self presentLoadingTips:nil];
    NSString *UDID= [[STISystemInfo deviceUUID] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSString *url = kLogIn;
    NSDictionary *params =@{
                            @"link_mobile":self.userTextfield.text,
                            @"expert_pwd":self.pwdTextfield.text,
                            @"visit_id":UDID,
                            @"yw_id":yw_id
                            };
    [DownloadData post:url params:params success:^(id json) {
        
        NSLog(@"json = %@",json);
   
        //只要进来我就认为登录成功了
        
        [WeakSekf dismissTips];
        NSString * expert_id = json[@"expert_id"];
        NSString *check_flag = json[@"check_flag"];
        
        if (expert_id==nil) {
            [WeakSekf   presentFailureTips:@"用户名或密码错误!"];
            return ;
        }
        
        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
        NSString *phone = [def objectForKey:KLINKMOBILE];
        
        
        //判断跟以前登录的手机号码是否一样
        if ([WeakSekf.userTextfield.text isEqualToString:@"13810534048"]){
            [WeakSekf  setUpLoginWithPhone:@"13810534048" WithExpertId:expert_id WithCheck_flag:check_flag WithIsLoginIn:YES];
            return ;
        }
        if ([phone isEqualToString:_userTextfield.text]){
            [WeakSekf  setUpLoginWithPhone:_userTextfield.text WithExpertId:expert_id WithCheck_flag:check_flag WithIsLoginIn:YES];
            return;
        }else{
            
            //说明已经更换了账号,应该清空上一个人的资料
            NSString *userPhone = [[NSUserDefaults standardUserDefaults] valueForKey:KLINKMOBILE];
            [YCSSKeychain saveValue:@"**" andKey:userPhone];
            ResetPhoneViewController *resetPhoneVC = [[ResetPhoneViewController alloc] init];
            resetPhoneVC.phone = WeakSekf.userTextfield.text;
            resetPhoneVC.checkFlag = check_flag;
            resetPhoneVC.expertId = expert_id;
            resetPhoneVC.pwd = self.pwdTextfield.text;
            [WeakSekf presentViewController:resetPhoneVC animated:YES completion:nil];
            
        }


        
    } failure:^(NSError *error) {
        [WeakSekf   dismissTips];
        [WeakSekf   presentFailureTips:@"用户名或密码错误!!"];
    }];
    
    
    
}


-(void)setUpLoginWithPhone:(NSString *)phone WithExpertId:(NSString *)expertid WithCheck_flag:(NSString *)check_flag WithIsLoginIn:(BOOL)isLogin {
    
    //保存登录手机号
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    
    [def setObject:phone forKey:KLINKMOBILE];
    [def setObject:expertid forKey:KEXPERTID];
    [def setObject:check_flag forKey:KCHECKFLAG];
   
    [YCUserTool sharedTools].linkMobile = (phone==nil?@"":phone);
    [YCUserTool sharedTools].expertID = (expertid==nil?@"":expertid);

    NSLog(@"%@--%@",phone,self.pwdTextfield.text);
    //将用户的密码保存
   BOOL ii = [YCSSKeychain saveValue:self.pwdTextfield.text andKey:phone];
    
    if (ii) {
        NSLog(@"保存成功");
    }
    
    [def synchronize];
    
    if (isLogin) {
        
        UIWindow *window= [UIApplication sharedApplication].keyWindow;
        
        YCTabbarViewController *hoVC = [[YCTabbarViewController alloc]init];
        
        window.rootViewController = hoVC;
    }

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}


-(void)validationChanged:(UITextField *)textfied
{
    if (textfied.text.length ==11) {
        [textfied resignFirstResponder];
        [self.pwdTextfield becomeFirstResponder];
        
    }
}




@end
